package com.yuzhe.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.yuzhe.model.Admin;
import com.yuzhe.service.AdminService;
import com.yuzhe.service.impl.AdminServiceImpl;
import com.yuzhe.utils.JSONResult;
import com.yuzhe.utils.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;

public class LoginController extends Controller {

    private AdminService adminService = new AdminServiceImpl();

    public void login(){
        String username = getPara("username");
        String password = getPara("password");



        if (StringUtils.isBlank(username)){
            renderJson(JSONResult.errorMsg("用户名不能为空"));
            return;
        }

        String sessionAttr = getSessionAttr(username);
        if (!StringUtils.isBlank(sessionAttr)){
            renderJson(JSONResult.ok(sessionAttr));
            return;
        }

        if (StringUtils.isBlank(password)){
            renderJson(JSONResult.errorMsg("密码不能为空"));
            return;
        }

        boolean userIsExist = adminService.checkUsernameIsExist(username);
        try {
            if (userIsExist){
                String sql = "select * from admin where username = ? and password = ? limit 1";
                Admin admin = Admin.dao.findFirst(sql,username, MD5Utils.getMD5Str(password));
                if (admin!=null){
                    String token = Sid.next();

                    Cache adminRedis = Redis.use("admin");
                    adminRedis.set(username,token);
                    token = adminRedis.get(username);
                    renderJson(JSONResult.ok(token));
                } else {
                    renderJson(JSONResult.errorMsg("用户名或密码错误"));
                }
            } else {
                renderJson(JSONResult.errorMsg("用户名不存在"));
            }
        } catch (Exception e) {

        }
    }

    public void logout () {
        String username = getPara("username");
        Cache adminRedis = Redis.use("admin");
        adminRedis.del(username);

        renderJson(JSONResult.ok());
    }

    public void userIsLogin () {
        String username = getPara("username");

        Cache adminRedis = Redis.use("admin");
        String token = adminRedis.get(username);

        renderJson(JSONResult.ok("用户名："+username+"token:"+token));
        if (!StringUtils.isBlank(token)){
            renderJson(JSONResult.ok(token));
        } else {
            renderJson(JSONResult.errorMsg("请登录"));
        }
    }

}
